package com.example.opencvdemo


import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import org.opencv.android.Utils
import org.opencv.core.Mat
import org.opencv.imgproc.Imgproc

private const val TAG = "CvtColorCompose"

@Composable
fun CvtColorCompose(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
//        verticalArrangement = Arrangement.SpaceAround
    ) {
        Image(
            bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.pic01)
                .asImageBitmap(), contentDescription = null
        )
        val bitmap = cvtColor(context, R.drawable.pic01)
        Image(bitmap = bitmap.asImageBitmap(), contentDescription = null)
    }
}

fun cvtColor(context: Context, image: Int): Bitmap {
    val bitmap = BitmapFactory.decodeResource(context.resources, image)
    val src = Mat()
    val dst = Mat()
    Utils.bitmapToMat(bitmap, src)
    // 转换为灰度图模式
    Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2GRAY)
    // 把mat转回bitmap
    Utils.matToBitmap(dst, bitmap)
    src.release()
    dst.release()
    return bitmap
}
